﻿/* 
 * BtCommLib - the OpenWebNet .NET Library
 *
 * Copyright (C) 2011 BTicino S.p.A.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BTicino.BtCommLib.Domain.LowLevel;
using BTicino.BtCommLib.Domain.Util;
using BTicino.BtCommLib.Trace;

namespace BTicino.BtCommLib.Communication
{
    public class BTOpenProtocolAdapter
    {
        #region Data Member
        
        private static BTLibLogger logger = BTLibLogger.createLogger("BTOpenProtocolAdapter");

        #endregion

        # region Constants

        /// <summary>
        /// Constants that describe the proper structure of the BTicino frames
        /// </summary>
        private const string _openRequest = "*{0}*{1}*{2}##"; //*CHI*COSA*DOVE##
        private const string _openRequestStatus = "*#{0}*{1}##"; //*#CHI*DOVE##
        private const string _openRequestDimension = "*#{0}*{1}*{2}##"; //*#CHI*DOVE*GRANDEZZA##
        private const string _openRequestWriteDimension = "*#{0}*{1}*#{2}{3}##"; //*#CHI*DOVE*#GRANDEZZA*VAL1*...*VALn##

        private const string _openEventStatusHead = "*";
        private const string _openEventStatusDimensionHead = "*#";

        private const string _openFrameValueSeparator = "*";
        private const int    _openFrameValueIndexPosition = 3;
        private const string _openFrameTail = "##";

        # endregion

        #region public methods

        /// <summary>
        /// Empty constructor
        /// </summary>
        public BTOpenProtocolAdapter() { }

        /// <summary>
        /// Traslator from BTOpenMessage to BTicino string message,
        /// see also #region Constants
        /// </summary>
        /// <param name="theMsg">BTOpenMessage to be translate</param>
        /// <returns>BTicino OPEN frmae</returns>
        public string FromMsgToFrame(BTOpenMessage theMsg)
        {
            //Check for Raw Frame
            if (theMsg.OpenRawMsg != null) 
            {
                return theMsg.OpenRawMsg;
            }

            
            string resultFrame = null;

            //Building Frame
            switch (theMsg.MsgType)
            {
                case BTOpenMsgType.Request:
                    resultFrame = string.Format(_openRequest, theMsg.Who, theMsg.What, theMsg.Where);
                    break;

                case BTOpenMsgType.RequestStatus:
                    resultFrame = string.Format(_openRequestStatus, theMsg.Who, theMsg.Where);
                    break;

                case BTOpenMsgType.RequestDimension:
                    resultFrame = string.Format(_openRequestDimension, theMsg.Who, theMsg.Where, theMsg.Dimension);
                    break;

                case BTOpenMsgType.RequestWriteDimension:
                    StringBuilder dimValuesStr = new StringBuilder();
                    for (int i = 0; i < theMsg.DimValues.Length; i++)
                    {
                        dimValuesStr.Append(_openFrameValueSeparator).Append(theMsg.DimValues[i]);
                    }
                    resultFrame = string.Format(_openRequestWriteDimension, theMsg.Who, theMsg.Where, theMsg.Dimension, dimValuesStr.ToString());
                    break;
            }

            return resultFrame;
        }

        /// <summary>
        /// Translator from BTicino OPEN frame to BTOpenMassage
        /// </summary>
        /// <param name="theFrame">BTicino OPEN frame</param>
        /// <returns>BTOpenMessage, if OPEN frame is syntactically correct, null otherwise</returns>
        public BTOpenMessage FromFrameToMsg(string theFrame) 
        {
            BTOpenMessage om = null;
            string bodyFrame = null;
            string[] tokens = null;


            //EventStatusDimension
            if (theFrame.StartsWith(_openEventStatusDimensionHead))
            {
                bodyFrame = theFrame.Substring(_openEventStatusDimensionHead.Length, theFrame.Length - _openEventStatusDimensionHead.Length - _openFrameTail.Length);
                logger.Debug("source: |" + theFrame + "| bodyFrame EventStatusDimension: |" + bodyFrame + "|");

                tokens = bodyFrame.Split(new string[] { _openFrameValueSeparator }, StringSplitOptions.None);

                //Get Dimension Values
                string[] tmpValues = new string[tokens.Length - _openFrameValueIndexPosition];
                Array.Copy(tokens, _openFrameValueIndexPosition, tmpValues, 0, tmpValues.Length);
                
                //Fill Low-Level Message
                om = new BTOpenMessage();
                om.MsgType = BTOpenEventMsgType.EventStatusDimension;
                om.Who = tokens[0];
                om.Where = tokens[1];
                om.Dimension = tokens[2];
                om.DimValues = tmpValues;
                om.OpenRawMsg = theFrame;

                //DEBUG
                foreach (var item in tokens)
                {
                    logger.Debug("frame token: " + item);
                }

                foreach (var item in tmpValues)
                {
                    logger.Debug("value token: " + item);
                }
            }
            //EventStatus
            else if (theFrame.StartsWith(_openEventStatusHead))
            {
                bodyFrame = theFrame.Substring(_openEventStatusHead.Length, theFrame.Length - _openEventStatusHead.Length - _openFrameTail.Length);
                logger.Debug("source: |" + theFrame + "| bodyFrame EventStatus: |" + bodyFrame + "|");

                tokens = bodyFrame.Split(new string[] { _openFrameValueSeparator }, StringSplitOptions.None);

                //Fill Low-Level Message
                om = new BTOpenMessage();
                om.MsgType = BTOpenEventMsgType.EventStatus;
                om.Who   = tokens[0];
                om.What  = tokens[1];
                om.Where = tokens[2];
                om.OpenRawMsg = theFrame;

                //DEBUG
                foreach (var item in tokens)
                {
                    logger.Debug("frame token: " + item);
                }
            }
            else
            {
                logger.Warn("Frame match not found: " + theFrame);
            }
            
            return om;
        }

        #endregion
    }
}
